package com.zk.shopping.base.interceptor;

import com.zk.shopping.base.utils.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

/**
 * 日志切面
 * Created by zhangkai on 2/26/16.
 */
public class LogInterceptor {

    private static final int RESULT_MAX_LENGTH = 80;

    Log logger =  LogFactory.getLog(LogInterceptor.class);

    @Around(value = "aspectjMethod()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        StringBuilder logMessage = new StringBuilder();
        long timeStart = System.currentTimeMillis();
        logMessage.append("\n--------------------\t" + DateUtils.format(timeStart) + "    -------------------\n");
        String classPath = pjp.getSignature().getDeclaringType().getName();
        logMessage.append("class    : " + classPath + "\n");
        String method = pjp.getSignature().getName();
        logMessage.append("method   : " + method + "\n");
        logMessage.append("input    : [");
        for(Object arg : pjp.getArgs()){
            logMessage.append(arg + ",");
        }
        logMessage.deleteCharAt(logMessage.length() - 1);
        logMessage.append("]\n");
        //调用核心逻辑
        Object retVal = pjp.proceed();
        if(retVal == null){
            logMessage.append("output   : null\n");
        }else if(retVal.toString().length() < RESULT_MAX_LENGTH) {
            logMessage.append("output   : " + retVal.toString() + "\n");
        }else{
            logMessage.append("output   : " + retVal.toString().substring(0, RESULT_MAX_LENGTH) + "...\n");
        }
        logMessage.append("costtime : " + (System.currentTimeMillis() - timeStart) + "ms\n");
        logMessage.append("-------------------------------------------------------------------\n");
        logger.info(logMessage);
        return retVal;
    }
}
